<template>
	<view>
		<view class="service-banner">
			<view class="service-banner__bg"></view>
			<view class="service-banner__main">
				<view class="service-banner__out">
					<view class="service-banner__in"></view>
				</view>
				<view class="service-banner__step">
					<view class="service-banner__item"
						v-for="(item,index) in stepsArr"
						:class="{'active':currentIndex == index}"
						:key="item.id">
						<text>{{item.title}}</text>
					</view>
				</view>
			</view>
		</view>
		<view class="service-main">
			<view class="service-main__head">
				<image class="service-main-avatar"
					:src="serviceDetailInfo.icon_image_url"
					mode="scaleToFill"></image>
				<view class="service-main-title">
					<text>{{serviceDetailInfo.name}}</text>
				</view>
				<view class="service-main-content">
					<text>服务内容</text>
				</view>
			</view>

			<block v-if="['10','15','20'].includes(serviceDetailInfo.stype)">
				<view class="form">
					<view class="form-item">
						<view class="form-item__left">
							<text>就诊医院</text>{{hIndex}}
						</view>
						<view class="form-item__right">
							<picker mode="selector"
								:range="hospitals"
								:value="hIndex"
								range-key="name"
								@change="handleChange">
								<input type="text"
									disable
									placeholder="请选择要就诊的医院"
									:value="hIndex>=0 && hospitals[hIndex].name || ''" />
							</picker>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item__left">
							<text>就诊日期选择</text>
						</view>
						<view class="form-item__right">
							<picker mode="date"
								@change="handleChangeDate"
								:value="date">
								<text>{{date}}</text>
							</picker>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item__left">
							<text>就诊时间选择</text>
						</view>
						<view class="form-item__right">
							<picker mode="time"
								@change="handleChangeTime"
								:value="time">
								<text>{{time}}</text>
							</picker>
						</view>
					</view>
					<view class="form-item"
						@click="handleSelectPerson">
						<view class="form-item__left">
							<text>就诊人</text>
						</view>
						<view class="form-item__right">
							<view class="">
								<input type="text"
									disabled
									v-model="clientsInfo.name"
									placeholder="请选择就诊人" />
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item__left">
							<text>接送地址</text>
						</view>
						<view class="form-item__right">
							<view class="">
								<input type="text"
									:value="clientsInfo.address"
									placeholder="请填写就诊人所在地址" />
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item__left">
							<text>联系电话</text>
						</view>
						<view class="form-item__right">
							<view class="">
								<input type="tel"
									:value="clientsInfo.mobile"
									:maxlength="11"
									placeholder="请填写您的联系电话" />
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item__left">
							<text>服务需求</text>
						</view>
						<view class="form-item__right">
							<view class="">
								<textarea :value="clientsInfo.desc"
									row="4"
									placeholder="请简单描述您要描述的就诊信息" />
							</view>
						</view>
					</view>
				</view>
			</block>
			<block v-else>
				<view class="form">
					<view class="form-item">
						<view class="form-item__left">
							<text>所在医院</text>
						</view>
						<view class="form-item__right">
							<picker mode="selector"
								:range="hospitals"
								:value="hIndex"
								range-key="name"
								@change="handleChange">
								<input type="text"
									disabled
									placeholder="请选择要就诊的医院"
									:value="hIndex>=0 && hospitals[hIndex]?.name || ''" />
							</picker>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item__left">
							<text>服务日期选择</text>
						</view>
						<view class="form-item__right">
							<picker mode="date"
								@change="handleChangeDate"
								:value="date">
								<text>{{date || "请选择服务的日期"}}</text>
							</picker>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item__left">
							<text>服务时间选择</text>
						</view>
						<view class="form-item__right">
							<picker mode="time"
								@change="handleChangeTime"
								:value="time">
								<text>{{time || "请选择服务的时间"}}</text>
							</picker>
						</view>
					</view>
					<view class="form-item"
						@click="handleGetAddress">
						<view class="form-item__left">
							<text>收件信息</text>
						</view>
						<view class="form-item__right">
							<view class="">
								<input type="text"
									disabled
									:value="userInfoAddress"
									placeholder="请填写您所在地址" />
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item__left">
							<text>联系电话</text>
						</view>
						<view class="form-item__right">
							<view class="">
								<input type="text"
									v-model="clientsInfo.mobile"
									placeholder="请填写您的联系电话" />
							</view>
						</view>
					</view>
					<view class="form-item">
						<view class="form-item__left">
							<text>服务需求</text>
						</view>
						<view class="form-item__right">
							<view class="">
								<textarea v-model="clientsInfo.desc"
									row="4"
									placeholder="请简单描述您要描述的就诊信息" />
							</view>
						</view>
					</view>
				</view>
			</block>

		</view>
		<view class="service-bottom">
			<view class="service-bottom__top">
				<checkbox-group @change="checkboxChange">
					<label>
						<checkbox class="round red"
							value="1"
							:checked="checked"></checkbox>
						<text style="vertical-align: middle;">我已阅读并同意</text>
					</label>
				</checkbox-group>
				<navigator url="/">《用户协议》</navigator>
				<text>和</text>
				<navigator url="/">《服务协议》</navigator>
			</view>
			<view class="submit-btn">
				<button form-type="submit"
					type="primary"
					:disabled="!checked"
					size="mini"
					@click="handleSubmit">
					确认下单
					<block v-if="orderData.price">(支付{{orderData.price}}元)</block>
				</button>
			</view>


		</view>
		<uni-popup ref="alertDialog"
			type="center"
			class="my-popup">
			<view class="popup-content">
				<view class="popup-content__item">
					<text class="text">手机号</text>
					<input type="text"
						v-model="sms.tel" />
				</view>

				<view class="popup-content__item">
					<text class="text">验证码</text>
					<input type="number"
						v-model="sms.code" />
					<text @click="handleCountTimeDown">{{isShowMsg ? '获取验证码':`剩余${countTime}s`}}</text>
				</view>
				<view class="popup-content__item">
					<button type="default"
						size="mini"
						@click="dialogClose">取消</button>
					<button size="mini"
						type="primary"
						@click="dialogConfirm">确认</button>
				</view>
			</view>
		</uni-popup>

		<uni-popup ref="scanDialog"
			type="center"
			class="my-popup">
			<view class="pay-box">
				<view class="pay-box__txt">
					微信支付
				</view>
				<canvas id="qrcode"
					canvas-id="qrcode"
					style="width: 300rpx;height: 300rpx;"></canvas>
				<view class="pay-box__txt"
					@click="handleToOrderLists">
					请用本人的微信扫码付款
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		computed,
		onMounted,
		reactive,
		ref,
		toRaw
	} from 'vue';
	import {
		onLoad,
		onReady
	} from "@dcloudio/uni-app"
	import {
		getServiceLists,
		createOrder,
		getAuthCode,
		verifyAuthCode
	} from '../../api'
	import UQRCode from 'uqrcodejs'
	const stepsArr = ref([{
			title: '填写订单',
			id: 1
		}, {
			title: '在线支付',
			id: 2
		},
		{
			title: '专人服务',
			id: 3
		},
		{
			title: '订单完成',
			id: 4
		}
	])

	const currentIndex = ref(0)
	const serviceDetailInfo = ref({})
	const hospitals = ref([])
	const hIndex = ref(0)
	const clientsInfo = ref({
		name: '',
		mobile: '',
		desc: ''
	})
	onLoad(async (options) => {
		const serviceData = {
			aid: options.aid,
			ssid: options.ssid,
			svid: options.svid
		}
		console.log('options', options.hid);
		const res = await getServiceLists(serviceData)
		console.log(res, 'service');
		serviceDetailInfo.value = res.data.service
		hospitals.value = res.data.hospitals
		// 默认选中
		hIndex.value = getDefaultIndex(res.data.hospitals, options.hid)

		uni.$on('clientsChange', data => {
			console.log('data', data);
			clientsInfo.value = data
		})
	})

	const orderData = reactive({
		price: 0,
		starttime: '',
		address: {
			username: '',
			cityName: '',
			countryName: '',
			detailInfo: ''
		}
	})

	const handleChange = e => {
		const {
			value
		} = e.detail
		hIndex.value = value
		console.log(toRaw(hospitals), 'hospitals');
		console.log(value, 'value');
		orderData.price = hospitals.value[value].service_price
	}

	const getDefaultIndex = (array, hid) => {
		let defaultIndex = -1
		for (let index = 0; index < array.length; index++) {
			const item = array[index];
			if (item.id == hid) {
				defaultIndex = index;
				orderData.price = item.service_price
				break
			}
		}
		return defaultIndex;
	}

	const date = ref('')
	const time = ref('')
	const handleChangeDate = e => {
		console.log(e, 'okok');
		date.value = e.detail.value
	}
	const handleChangeTime = e => {
		console.log(e, 'okok');
		time.value = e.detail.value
	}

	const handleSelectPerson = () => {
		uni.navigateTo({
			url: "/pages/clients/index?act=select"
		})
	}

	const checked = ref(true)
	const checkboxChange = e => {
		checked.value = !!e.target.value.length
	}

	const handleGetAddress = () => {
		console.log(898989);
		uni.chooseAddress({
			fail: (res) => {
				console.log(res, '45454545');
			},
			success: (res) => {
				orderData.address.username = res.userName
				orderData.address.cityName = res.cityName
				orderData.address.countyName = res.countyName
				orderData.address.detailInfo = res.detailInfo
			}
		})
	}

	const userInfoAddress = computed(() => {
		let stringName = ''
		const data = orderData.address
		for (let key in data) {
			stringName += data[key]
		}
		return stringName
	})
	const alertDialog = ref(null)
	const scanDialog = ref(null)
	const handleSubmit = async () => {
		const hospitalName = hospitals.value[hIndex.value]?.name
		console.log('hospitalName', hospitalName);
		if (!hospitalName) {
			return uni.showToast({
				title: '就诊医院不能为空',
				icon: 'error'
			})
		}
		if (!date.value || !time.value) {
			return uni.showToast({
				title: '就诊日期时间不能为空',
				icon: 'error'
			})
		}

		if (['10', '15', '20'].includes(serviceDetailInfo.value.stype)) {
			// return uni.showToast({
			// 	title: '就诊日期时间不能为空',
			// 	icon: 'error'
			// })
		} else {
			if (!orderData.address.username) {
				return uni.showToast({
					title: '收件信息不能为空',
					icon: 'error'
				})
			}
		}
		// 联系电话不能为空
		if (!clientsInfo.value.mobile) {
			return uni.showToast({
				title: '联系电话不能为空',
				icon: 'error'
			})
		} else if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(clientsInfo.value.mobile)) {
			return uni.showToast({
				title: '联系电话格式不对',
				icon: 'error'
			})
		}


		if (!clientsInfo.value.desc) {
			return uni.showToast({
				title: '服务需求不能为空',
				icon: 'error'
			})
		}
		if (!uni.getStorageSync()) {
			alertDialog.value.open()
		} else {
			handleSubmitOrder()
		}

	}

	const sms = reactive({
		tel: '',
		code: ''
	})
	const isShowMsg = ref(true)
	const countTime = ref(10)
	const timer = ref(null)
	const dialogConfirm = () => {
		if (!sms.code) {
			return uni.showToast({
				title: "验证码不能为空",
				icon: 'error'
			})
		}
		uni.setStorageSync('token', "cdeb727638b86f08d20a2f703389865f")
		verifyAuthCode(sms).then(res => {
			// cdeb727638b86f08d20a2f703389865f
			console.log('xscode', res);
			uni.setStorageSync('token', res.data.token)
			handleSubmitOrder()
		})
	}

	const dialogClose = () => {
		clearInterval(timer.value)
		alertDialog.value.close()
	}
	const isCounting = ref(false)
	const handleCountTimeDown = () => {
		if (isCounting.value) return false
		if (!sms.tel) {
			return uni.showToast({
				title: "手机号不能为空",
				icon: 'error'
			})
		}
		isShowMsg.value = false
		isCounting.value = true
		getAuthCode({
			tel: sms.tel
		}).then(res => {
			console.log(res, 'yanzhengma');
		})
		timer.value = setInterval((() => {
			countTime.value--;
			if (countTime.value == 0) {
				clearInterval(timer.value)
				isShowMsg.value = true
				countTime.value = 10
				isCounting.value = false
			}
		}), 1000)
	}

	const handleSubmitOrder = async () => {
		const paramData = {
			"address": orderData.address,
			"demand": clientsInfo.value.desc,
			"hospital_id": hospitals.value[hIndex.value].id,
			"hospital_name": hospitals.value[hIndex.value].name,
			"receiveAddress": userInfoAddress.value,
			"service_code": serviceDetailInfo.value.code,
			"service_id": hospitals.value[hIndex.value].service_id,
			"service_name": serviceDetailInfo.value.name,
			"service_stype": serviceDetailInfo.value.stype,
			"starttime": new Date(date.value + " " + time.value).getTime(),
			"tel": clientsInfo.value.mobile,
			"client": {
				"age": 0,
				"mobile": "",
				"name": "",
				"sex": 0
			}
		}

		const resultInfo = await createOrder(paramData).catch(err => {
			uni.clearStorageSync('token')
		})
		uni.showToast({
			title: resultInfo.msg
		})
		alertDialog.value.close()
		scanDialog.value.open('center')
		createQCode(resultInfo)
	}

	const createQCode = (resultInfo) => {
		// 获取uQRCode实例
		const qr = new UQRCode();
		// 设置二维码内容
		qr.data = resultInfo.wx_code;
		// 设置二维码大小，必须与canvas设置的宽高一致
		qr.size = 150;
		// 调用制作二维码方法
		qr.make();
		// 获取canvas上下文
		const canvasContext = uni.createCanvasContext('qrcode'); // 如果是组件，this必须传入
		// 设置uQRCode实例的canvas上下文
		qr.canvasContext = canvasContext;
		// 调用绘制方法将二维码图案绘制到canvas上
		qr.drawCanvas();
	}

	const handleToOrderLists = () => {
		uni.switchTab({
			url: "/pages/order/order"
		})
	}
</script>

<style lang="scss"
	scoped>
	.service-banner {
		position: relative;

		&__bg {
			height: 240rpx;
			background: linear-gradient(to right, #007d65, #45b97c);
			position: absolute;
			top: 0;
			left: 0;
			right: 0;

		}

		&__main {
			position: relative;
			overflow: hidden;

			.service-banner__out {
				width: 80%;
				margin: 60rpx auto 30rpx;
				height: 16px;
				background-color: #fff;
				border-radius: 10px;
				box-sizing: border-box;
				box-shadow: #007d65 2px 2px 10px;
				display: flex;
				padding: 2px;
				transition: width .5s ease-in;

				.service-banner__in {
					border-radius: 10px;
					width: 25%;
					background: linear-gradient(to right, #007d65, #45b97c);
				}
			}

			.service-banner__step {
				width: 70%;
				margin: 60rpx auto 30rpx;
				display: flex;
				justify-content: space-between;

				.service-banner__item {
					font-size: 24rpx;
					color: #ececec;

					&.active {
						color: #fff;
						font-weight: bold;
					}
				}
			}
		}
	}

	.service-main {
		position: relative;
		width: 90%;
		background-color: #fff;
		margin: -4rpx auto 0;
		border-radius: 10rpx;

		&__head {
			padding: 20rpx;
			display: flex;
			align-items: center;

			.service-main-avatar {
				width: 40rpx;
				height: 40rpx;
				margin-right: 10rpx;
			}

			.service-main-title {
				font-weight: bold;
			}

			.service-main-content {
				margin-left: auto;
				color: #999;
				font-size: 26rpx;
			}
		}

		.form {
			&-item {
				margin: 20rpx 0 40rpx;
				display: flex;
				justify-content: space-between;


				&__right {
					text-align: right;
					color: #999;
				}

				&:last-child {
					flex-direction: column;

					justify-content: flex-start;
					gap: 30rpx 0;

					textarea {
						text-align: left;
						border: 1rpx solid #ccc;
						border-radius: 10rpx;
						padding: 20rpx;
						height: 150rpx;
						flex: 1;
					}
				}
			}
		}

		padding-bottom: 200rpx;
	}

	.service-bottom {
		height: 150rpx;
		background-color: #f3f3f3;
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;

		&__top {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 20rpx 0 10rpx;
			font-size: 24rpx;

			.round {
				transform: scale(0.5);
			}

			.uni-list-cell {
				line-height: 1;
			}


			.navigator {
				color: green;
				text-decoration: underline;
			}
		}

		.submit-btn {
			text-align: center;
		}
	}

	.popup-content {
		background-color: #fff;
		padding: 30rpx;
		// width: 96%;
		height: 300rpx;

		&__item {
			display: flex;
			margin: 40rpx auto;
			gap: 10rpx 20rpx;
		}
	}

	.pay-box {
		background-color: #fff;
		padding: 20rpx;

		&__txt {
			text-align: center;
			margin: 10rpx 0;
			font-size: 26rpx;
		}
	}
</style>